package Test;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.concurrent.ConcurrentLinkedDeque;

//实现一个最简版的固定大小线程池 MiniFixedThreadPool，要求：
//        1. 构造：MiniFixedThreadPool(int nThreads)
//2. 方法：submit(Runnable task)
//3. 方法：shutdown()
//  - 调用后不再接受新任务
//  - 已提交的任务继续执行
//4. 线程复用：预先创建 nThreads 个工作线程，循环取任务执行
//5. 任务队列：若使用无界队列，可暂不做拒绝策略
//
//约束：
//        - 不允许直接使用 java.util.concurrent 包里的现成线程池（如 ThreadPoolExecutor）
//        - 可以使用：synchronized / wait / notify / volatile / Thread / List / Queue
public class MyExec {
    volatile boolean isShuttingDown = false;
    //固定的线程
    int fixedTheadCount = 0;
    //线程队列
    HashMap<Integer,Thread> map;
    //线程状态
    HashMap<Integer,Boolean> threadActive;
    //任务队列
    Deque<Runnable> runnableDeque;
    public MyExec(int fixedTheadCount){
        this.fixedTheadCount = fixedTheadCount;
        runnableDeque = new ConcurrentLinkedDeque<>();
        threadActive = new HashMap<>();
        map = new HashMap<>();
        for (int i = 0; i < fixedTheadCount; i++) {
            map.put(i,new Thread());
            threadActive.put(i,true);
        }
    }
    public void submit(Runnable runnable){
        runnableDeque.offer(runnable);
    }
    public void shutdown(){
        isShuttingDown = true;
    }
    public void execute(){
        while(!runnableDeque.isEmpty() && !isShuttingDown){
            Runnable r =  runnableDeque.poll();
            for(int threadIndex : map.keySet()){
                if (threadActive.get(threadIndex)){
                    Thread curThread = map.get(threadIndex);
//                    curThread.setRunable(r);
                    curThread.start();
                    if (curThread.isAlive()){
                        threadActive.put(threadIndex,false);
                    }
                }
            }
        }
    }
}
